package com.shunli.cterminal.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.examples.core.enums.OrderPaymentModeEnum;
import com.examples.core.tool.constant.AdPushConstants;
import com.examples.core.tool.constant.ExamplesConstants;
import com.shunli.cterminal.entity.SystemOrderAdTemp;
import com.shunli.cterminal.enums.OrderV2StatusEnum;
import com.shunli.cterminal.mapper.SystemOrderAdTempMapper;
import com.shunli.cterminal.model.ExtJson3;
import com.shunli.cterminal.model.dto.OrderEtlData;
import com.shunli.cterminal.model.req.PushOrderReq;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static com.examples.core.tool.utils.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;

/**
 * @ClassName: OrderDataEtlService
 * @Description: TODO 订单数据抽取
 * @Author: DAIYALU
 * @Date: 2024/9/19
 * @Version: 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderDataEtlService {

    private final SystemOrderAdTempMapper adTempMapper;
    private final RedissonClient redissonClient;

    public void orderDataHandler(SystemOrderAdTemp adTemp,PushOrderReq req){
        log.info("orderDataHandler,adTemp:{},req:{}", adTemp, req);
        OrderEtlData data = null;
        // 在线订单
        data = queryWaitPayOrderData(adTemp,req.getOrderNo(),req.getAdChannelCode()) ;
        log.info("orderDataHandler,data:{}", data);
        if(null == data){
            return;
        }
        try{
            String key = AdPushConstants.ORDER_STATUS_PUSH_KEY + req.getOrderNo() + StringPool.COLON + System.currentTimeMillis();
            RBucket<String> pushBucket = redissonClient.getBucket(key);
            pushBucket.set(JSONUtil.toJsonStr(data),30, TimeUnit.MINUTES);
            log.info("orderDataHandler,key:{}", key);
        }catch (Exception e){
            log.error("orderDataHandler,缓存数据失败，订单号：【{}】，订单数据【{}】",req.getOrderNo(),JSONUtil.toJsonStr(data));
        }
    }

    private OrderEtlData queryWaitPayOrderData(SystemOrderAdTemp adTemp, String orderNo,String adChannelCode) {
        if(null == adTemp){
            adTemp = adTempMapper.selectOne(Wrappers.<SystemOrderAdTemp>lambdaQuery()
                    .eq(SystemOrderAdTemp::getEncryptionOrder,orderNo).orderByDesc(SystemOrderAdTemp::getId).last(ExamplesConstants.EXAM_MYSQL_LIMIT));
        }
        if(null == adTemp){
            return null;
        }
        OrderEtlData data = new OrderEtlData();// 订单基础信息
        data.setUid(adTemp.getUid());
        data.setOrderNo(orderNo);
        data.setMallCode("ad");
        data.setAppCode("H5");
        if(StrUtil.isNotBlank(adTemp.getExtJson3())){
            ExtJson3 extJson3 = JSONUtil.toBean(adTemp.getExtJson3(),ExtJson3.class);
            data.setMallCode(Optional.ofNullable(extJson3.getMallCode()).orElse(data.getMallCode()));
        }
        data.setPaymentMode(OrderPaymentModeEnum.FULL.getCode());
        data.setTemplateNo(adTemp.getOrderFname());
        data.setReceivableAmount(Optional.ofNullable(adTemp.getRealAmount()).orElse(BigDecimal.ZERO));
        data.setDomain(adTemp.getUrlName());
        data.setAdChannelCode(adChannelCode);
        data.setCreateTime(null != adTemp.getCreateTime() ? DateUtil.format(adTemp.getCreateTime(), FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) : null);
        data.setOrderItem(Lists.newArrayList());
        data.setStatus(OrderV2StatusEnum.AIT_PAY.getCode());
        data.setTgPar(adTemp.getTgPar());
        OrderEtlData.SubOrderData subOrder = new OrderEtlData.SubOrderData();// 子订单信息
        subOrder.setMainOrderId(data.getId());
        subOrder.setMainOrderNo(data.getOrderNo());
        subOrder.setOrderId(data.getId());
        subOrder.setOrderNo(data.getOrderNo());
        subOrder.setOrderPrice(data.getReceivableAmount());
        subOrder.setCreateTime(data.getCreateTime());
        subOrder.setStatus(data.getStatus());
        subOrder.setGoodsItem(Lists.newArrayList());
        OrderEtlData.OrderGoodsData goodsData = new OrderEtlData.OrderGoodsData();
        goodsData.setId(IdUtil.getSnowflakeNextId());
        goodsData.setMainOrderId(data.getId());
        goodsData.setMainOrderNo(data.getOrderNo());
        goodsData.setOrderId(data.getId());
        goodsData.setOrderNo(data.getOrderNo());
        goodsData.setGoodsId(null != adTemp.getGoodsId() ? Long.valueOf(adTemp.getGoodsId()) : null);
        goodsData.setNumber(1);
        goodsData.setGoodsPrice(data.getReceivableAmount());
        goodsData.setCreateTime(data.getCreateTime());
        goodsData.setGoodsName(adTemp.getGoodsName());
        goodsData.setShipWay(adTemp.getFhType());
        goodsData.setShipStatus(Optional.ofNullable(adTemp.getDelivery()).orElse(0).toString());
        subOrder.getGoodsItem().add(goodsData);
        data.getOrderItem().add(subOrder);
        return data;
    }

}
